//
//  SystemMessageViewController.m
//  HAHAWENWAN
//
//  Created by 李小龙 on 2017/9/14.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "SystemMessageViewController.h"
#import "SystemMessageTableViewCell.h"
#import "MessageModel.h"
#import "OrderModel.h"
//#import "EditSendViewController.h"
#import "OrderDetailViewController.h"
#import "RefundDetailViewController.h"
#import "NotificationViewController.h"

@interface SystemMessageViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<MessageSystemModel *> *tableArray;
@property (nonatomic, assign) NSInteger page;

@end

@implementation SystemMessageViewController
#pragma mark - Get
- (NSMutableArray<MessageSystemModel *> *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
    }
    return _tableArray;
}
#pragma mark - ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"系统消息";
    [self hiddenShadowImage:NO];
    
    self.page = 1;
    [self createTableView];
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self getNetData];
    
    [UserInfo shareInstance].user.showBadge = NO;
    [[UserInfo shareInstance] updateUserModel];
    [(AppDelegate *)[UIApplication sharedApplication].delegate updateBadgeValue:NO];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}
#pragma mark -
static NSString *messageTableIdentifier = @"systemMessageTableIdentifier";
- (void)createTableView {
    [self.tableView registerNib:[UINib nibWithNibName:@"SystemMessageTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:messageTableIdentifier];
    [self.tableView clearExtendCellLine];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [self getNetData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getNetData];
    }];
    [self.tableView.mj_footer setHidden:YES];
}
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)getNetFailure {
    if (_page != 1) {
        _page--;
    }
}
- (void)getNetSuccess:(NSDictionary *)dics {
    
    if ([dics[@"totalRow"] integerValue] > self.tableArray.count) {
        [self.tableView.mj_footer setHidden:NO];
    } else {
        [self.tableView.mj_footer setHidden:YES];
    }
    
    if (self.page == 1) {
        [self.tableArray removeAllObjects];
        [self.tableView.mj_footer resetNoMoreData];
    }
    // 数据列表
    MessageModel *model = [MessageModel mj_objectWithKeyValues:dics[@"data"]];
    if (model.list.count == 0 && self.page != 1) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self getNetFailure];
        return;
    }
    
    [self.tableArray addObjectsFromArray:model.list];
    [self.tableView reloadData];
}
#pragma mark - 网络请求
- (void)getNetData {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:PageSize forKey:@"pageSize"];
    [dic setObject:@(_page) forKey:@"pageNumber"];
    
    // 获取我的消息列表接口
    [MYAFNetworking POST:URL_Get_Infomation parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [self endRefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *dics = responseObject;
            [self getNetSuccess:dics];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"data"] animated:YES];
            [self getNetFailure];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [self endRefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
        [self getNetFailure];
    }];
}
- (void)uploadSaveInfomation:(MessageSystemModel *)model {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Save_Information parameters:@{@"iid":model.iid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            model.istatus = YES;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}
- (void)deleteInfomation:(MessageSystemModel *)model indexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    [parameters safeSetObject:model.iid forKey:@"iid"];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Delete_Information parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            
            [weakSelf.tableArray removeObjectAtIndex:indexPath.section];
            
            // 适配iOS11
            if (@available(iOS 11.0, *)) {
                [weakSelf.tableView performBatchUpdates:^{
                    [weakSelf.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
                } completion:^(BOOL finished) {
                    [weakSelf.tableView reloadData];
                }];
            } else {
                [weakSelf.tableView beginUpdates];
                [weakSelf.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
                [weakSelf.tableView endUpdates];
            }
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.tableArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SystemMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:messageTableIdentifier forIndexPath:indexPath];
    
    MessageSystemModel *model = self.tableArray[indexPath.section];
    [cell.titleLabel setText:model.ititle];
    [cell.contentLabel setText:model.icontent];
    if (model.istatus) {
        // 已读
        [cell.titleLabel setTextColor:[UIColor grayTextColor]];
        [cell.contentLabel setTextColor:[UIColor grayTextColor]];
    } else {
        // 未读
        [cell.titleLabel setTextColor:[UIColor blackTextColor]];
        [cell.contentLabel setTextColor:[UIColor grayTextColor]];
    }
    [cell.backView setCircleWithColor:[UIColor clearColor] borderWidth:0 cornerRadius:5];
    
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 35;
    }
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MessageSystemModel *model = self.tableArray[section];
    
    UILabel *label = [[UILabel alloc] init];
    [label setText:[DateSomeThing getDateStrWithTimestampstr:model.createtime formatStr:@"yyyy-MM-dd"]];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setTextColor:[UIColor grayTextColor]];
    [label setFont:TextPingFangFontSize(14)];
    return label;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageSystemModel *model = self.tableArray[indexPath.section];
    // 调用已读接口
    [self uploadSaveInfomation:model];
    // 根据类型跳转界面 消息类型（1发货 2退款）（1提醒发货，2修改价格，3发货，4已退款，5系统消息，6退款驳回）
    switch (model.itype.integerValue) {
//        case 1:
//        {
////            EditSendViewController *editSendVC = [[EditSendViewController alloc] init];
////            OrderModel *temp = [[OrderModel alloc] init];
////            temp.osid = model.remark;
////            editSendVC.detailModel = temp;
////            [self.navigationController pushViewController:editSendVC animated:YES];
//        } break;
        case 1:
        {
            OrderModel *temp = [[OrderModel alloc] init];
            temp.omid = model.remark;
            OrderDetailViewController *orderDetailVC = [[OrderDetailViewController alloc] init];
            orderDetailVC.detailModel = temp;
            orderDetailVC.fromType = FromTypeSelfOrder;
            [self.navigationController pushViewController:orderDetailVC animated:YES];
        } break;
        case 2:
        {
            OrderModel *temp = [[OrderModel alloc] init];
            temp.ogid = model.remark;
            RefundDetailViewController *orderDetailVC = [[RefundDetailViewController alloc] init];
            orderDetailVC.detailModel = temp;
            [self.navigationController pushViewController:orderDetailVC animated:YES];

        } break;
        case 5:
        {
            NotificationViewController *notificationVC = [[NotificationViewController alloc] init];
            notificationVC.detailModel = model;
            [self.navigationController pushViewController:notificationVC animated:YES];
        } break;
        default:
            break;
    }
}
#pragma mark - 左滑删除
// 左滑删除
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

//左滑点击事件
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {  //删除事件
        
    }
}

-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    UITableViewRowAction *button = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        [self showAlertWithTitleArray:@[@"取消",@"确认"] title:@"温馨提示" message:@"确认删除该消息吗？" alertStyle:UIAlertControllerStyleAlert];
        self.alertBlock = ^(NSString *actionTitle) {
            if ([actionTitle isEqualToString:@"确认"]) {
                MessageSystemModel *model = [weakSelf.tableArray safeObjectAtIndex:indexPath.section];
                [weakSelf deleteInfomation:model indexPath:indexPath];
            }
        };
        NSLog(@"Action to perform with Button 1");
    }];
    //    button.backgroundColor = [UIColor ThemeColor]; //arbitrary color
    return @[button];
}
#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无消息"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    //    [self startLoadingGifView];
    _page = 1;
    [self getNetData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
